import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, In, Like } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateOrderDto, UpdateOrderDto, QueryOrderDto } from './dto/order.dto';
import { OrderEntity } from './entities/order.entity';
import { isEmpty } from 'src/common/utils';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(OrderEntity)
    private readonly orderEntityRep: Repository<OrderEntity>,
  ) {}

  async create(createOrderDto: CreateOrderDto) {
    const res = await this.orderEntityRep.save(createOrderDto);
    return ResultData.ok(res);
  }

  async findAll(query: QueryOrderDto) {
    const entity = this.orderEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (!isEmpty(query.id)) {
      entity.andWhere('entity.id = :id', { id: query.id });
    }
    if (!isEmpty(query.orderNo)) {
      entity.andWhere('entity.orderNo = :orderNo', { orderNo: query.orderNo });
    }
    if (!isEmpty(query.userId)) {
      entity.andWhere('entity.userId = :userId', { userId: query.userId });
    }
    if (!isEmpty(query.totalAmount)) {
      entity.andWhere('entity.totalAmount = :totalAmount', { totalAmount: query.totalAmount });
    }
    if (!isEmpty(query.payAmount)) {
      entity.andWhere('entity.payAmount = :payAmount', { payAmount: query.payAmount });
    }
    if (!isEmpty(query.discountAmount)) {
      entity.andWhere('entity.discountAmount = :discountAmount', { discountAmount: query.discountAmount });
    }
    if (!isEmpty(query.orderStatus)) {
      entity.andWhere('entity.orderStatus = :orderStatus', { orderStatus: query.orderStatus });
    }
    if (!isEmpty(query.payType)) {
      entity.andWhere('entity.payType = :payType', { payType: query.payType });
    }
    if (!isEmpty(query.productName)) {
      entity.andWhere('entity.productName LIKE :productName', { productName: `%${query.productName}%` });
    }
    if (!isEmpty(query.productDesc)) {
      entity.andWhere('entity.productDesc = :productDesc', { productDesc: query.productDesc });
    }
    if (!isEmpty(query.payTime)) {
      entity.andWhere('entity.payTime BETWEEN :start AND :end', { start: query.payTime[0], end: query.payTime[1] });
    }
    if (!isEmpty(query.cancelTime)) {
      entity.andWhere('entity.cancelTime BETWEEN :start AND :end', { start: query.cancelTime[0], end: query.cancelTime[1] });
    }
    if (!isEmpty(query.closeTime)) {
      entity.andWhere('entity.closeTime BETWEEN :start AND :end', { start: query.closeTime[0], end: query.closeTime[1] });
    }
    if (!isEmpty(query.remark)) {
      entity.andWhere('entity.remark = :remark', { remark: query.remark });
    }
    if (!isEmpty(query.createTime)) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', { start: query.createTime[0], end: query.createTime[1] });
    }
    if (!isEmpty(query.updateTime)) {
      entity.andWhere('entity.updateTime BETWEEN :start AND :end', { start: query.updateTime[0], end: query.updateTime[1] });
    }
    entity.select([
      'entity.id',
      'entity.orderNo',
      'entity.userId',
      'entity.totalAmount',
      'entity.payAmount',
      'entity.discountAmount',
      'entity.orderStatus',
      'entity.payType',
      'entity.productName',
      'entity.productDesc',
      'entity.payTime',
      'entity.cancelTime',
      'entity.closeTime',
      'entity.remark',
    ]);

    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    if (query.pageNum && query.pageSize) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }

    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findOne(id: number) {
    const res = await this.orderEntityRep.findOne({
      where: {
        id: id,
      },
    });
    return ResultData.ok(res);
  }

  async findOneByorderNo(orderNo: string) {
    const res = await this.orderEntityRep.findOne({
      where: {
        orderNo: orderNo,
      },
    });

    return res;
  }

  async update(updateOrderDto: UpdateOrderDto) {
    const res = await this.orderEntityRep.update({ id: updateOrderDto.id }, updateOrderDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  // async remove(ids: number[]) {
  //   const res = await this.orderEntityRep.update(
  //     { id: In(ids) },
  //     {
  //       delFlag: '1',
  //     },
  //   );
  //   return ResultData.ok({ value: res.affected >= 1 });
  // }

  /**
   * 更新订单状态
   * @param orderNo 订单编号
   * @param status 订单状态: 0-待支付，1-已支付，2-已取消，3-已关闭，4-已退款
   * @param transactionId 微信支付订单号
   * @param payTime 支付时间
   * @returns
   */
  async updateOrderStatus(orderNo: string, status: number, transactionId: string, payTime: Date) {
    try {
      // 根据订单编号查找订单
      const order = await this.orderEntityRep.findOne({
        where: {
          orderNo: orderNo,
        },
      });

      if (!order) {
        return false;
      }

      // 更新订单状态和支付时间
      const updateData: any = {
        orderStatus: status,
        transactionId: transactionId,
      };

      // 如果是支付成功状态，更新支付时间和微信订单号
      if (status === 1) {
        updateData.payTime = payTime;
      }

      const res = await this.orderEntityRep.update({ orderNo: orderNo }, updateData);

      return res.affected > 0;
    } catch (error) {
      console.error('更新订单状态失败:', error);
      return false;
    }
  }

  /**
   * 根据订单编号查询用户
   * @param out_trade_no 订单编号
   * @returns 用户信息
   */
  async findUserByOrderNo(out_trade_no: string) {
    const sql = `
    SELECT ci.user_id userId, ci.status, ci.end_time endTime
    FROM child_info ci
    INNER JOIN \`order\` o ON ci.user_id = o.user_id AND ci.del_flag = '0'
    WHERE o.order_no = ?
  `;
    const res = await this.orderEntityRep.query(sql, [out_trade_no]);
    return res && res.length > 0 ? res[0] : null;
  }
}
